/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package torrent;

/**
 *
 * @author THIEUQUANG
 */
import java.io.File;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.net.SocketException;

public class Core extends Function implements Runnable {

    public SocketAddress sk = null;
    boolean valueSet = false;

    public DatagramPacket receivedPacket;
    public byte[] receivedBuf;

    public Core(byte[] receivedBuf, DatagramPacket receivedPacket) {
        this.receivedBuf = receivedBuf;
        this.receivedPacket = receivedPacket;
    }

    public void run() {
        try {

            analyzerecieve();
        } catch (InterruptedException | IOException e) {
        }
    }

    void analyzerecieve() throws InterruptedException, IOException {
        InetAddress[] peerstore = new InetAddress[5];
        int curpeer = 0;
        int connected = 1;
        try {
            String fx = receivedPacket.getAddress().toString();// cat address thanh dang chuan x.x.x.x
            fx = fx.substring(1);
            // loai bo client nhan broadcast cua chinh no
            if (!fx.equals(
                    InetAddress.getLocalHost().getHostAddress())) {
                String ms = new String(receivedBuf);

                String[] res = ms.split(" ");
                String fn = res[0];
                String fe = res[1];
                if (res[2].equals("CHK")) {
                        // liet ke danh sach file hien co

                    File f = new File("rsc//");
                    String[] List;
                    List = f.list();
                    boolean flag = false;
                    for (String List1 : List) {
                        // kiem tra xem co ton tai file dang dc yeu cau
                        if (List1.toString().equals(fn + "." + fe + ".chunk")) {
                            flag = true;
                        }
                    }

                    if (flag == true) {
                        System.out.println("File found on server");
                        // gui goi tin FFOS
                        String Messagetosend = fn + " " + fe + " FFOS"
                                + " .";
                        InetAddress x = InetAddress.getByName(fx);
                        Broadcastsender(x, Messagetosend);
                        // ana = new Thread(new Analyzer(fn,"send", 1));
                    } else {
                    }
                }
                if (res[2].equals("REQ")) {
                    System.out.println("Sending confirm");
                    InetAddress x = InetAddress.getByName(fx);
                    DatagramSocket send = null;
                    int freeport = Findds(send);
                    String Messagetosend = fn + " " + fe + " CONF" + " " + res[3].toString() + " " + freeport + " .";
                    Broadcastsender(x, Messagetosend);
                    // goi ham gui chunk thu fe cua file fx, den x
                    Thread.sleep(500);
                    ana = new Thread(new Analyzer(fn, "send", Integer.parseInt(fe), x, freeport, Integer.parseInt(res[3].toString())));
                    ana.start();
                    //System.out.println("REQING");
                }
                if (res[2].equals("FFOS")) {

                    InetAddress x = InetAddress.getByName(fx);
                    // luu cac may chua file dc yeu cau vao peerstore
                    peerstore[curpeer] = x;
                    curpeer++;
                    if (connected == 1) {
                        System.out.println("Sending request");
                        // chi gui REQ 1 lan duy nhat cho 1 file, cai nay phai la array moi dung
                        DatagramSocket recv = null;
                        int freeport = Findds(recv);//port ben yeu cau dang free
                        String Messagetosend = fn + " " + fe + " REQ" + " " + freeport + " .";
                        //chon peer dau tien
                        Broadcastsender(peerstore[0], Messagetosend);
                        connected = 0;
                    }
                }
                if (res[2].equals("CONF")) {
                    System.out.println("reieve conf");
                    InetAddress x = InetAddress.getByName(fx);
                    //goi ham nhan file
                    ana = new Thread(new Analyzer(fn, "recv",
                            Integer.parseInt(fe), x, Integer.parseInt(res[3].toString()), Integer.parseInt(res[4].toString())));
                    ana.start();
                    connected = 1;
                }
            }
            Thread t = new Thread(this);
            t.interrupt();
        } catch (IOException e) {
            utpSocket.close();
        }
    }

    void Broadcastsender(InetAddress x, String Messagetosend) {
        // dung de gui thong diep
        try {

            int chunk = 1;
            byte[] sentBuf = new byte[100];
            sentBuf = Messagetosend.getBytes("ascii");
            int i = 0;
            while (true) {
                DatagramPacket sentPacket = new DatagramPacket(sentBuf,
                        sentBuf.length, x, 3400);
                utpSocket.send(sentPacket);
                i++;
                break;
            }
        } catch (IOException e) {
            utpSocket.close();
        }
    }

    private int Findds(DatagramSocket ds) {

        int rand = 0;
        boolean f = true;
        while (f) {
            rand = (int) (Math.random() * 50000 + 1000);
            System.out.println(rand);
            try {
                ds = new DatagramSocket(rand);
                f = false;
                ds.close();
            } catch (SocketException e) {
            }
        }
        return rand;
    }

    public static void stopthread() {
        ana.interrupt();
    }
}
